package com.light.gulimall.auth.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.light.common.constants.Result;
import com.light.common.utils.R;
import com.light.common.vo.MemberRespVO;
import com.light.gulimall.auth.dto.LoginDTO;
import com.light.gulimall.auth.service.LoginService;
import com.light.gulimall.auth.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class LoginController {


    @Autowired
    private LoginService loginService;


    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        String code = UUID.randomUUID().toString().substring(0, 4);

        //接口防刷
        //验证码再次校验
        return loginService.sendMessageCode(phone, code);

    }


    @PostMapping("/regist")
    public String regist(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        //此处为可能存在的校验条件异常
        if (result.hasErrors()) {
            //收集错误信息返回到前端
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            // 如果是转发，会存在问题。因为前端请求本接口的方式是post，而转发的GulimallWebConfig中的配置，默认是Get请求，请求方式不匹配
            //当跳转到下一个页面取出数据之后，session中的数据就会被清理掉
            // 分布式存在session共享问题
            return "redirect:http://auth.gulimall.com/register.html";
        }

        //校验验证码
        R r = loginService.checkCode(vo);
        //返回错误信息
        if (r.get("code").equals(Result.ERROR)) {
            HashMap<String, String> map = new HashMap<>();
            map.put("code", (String) r.get("msg"));
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/register.html";
        }

        //注册
        R register = loginService.register(vo);
        Integer code = (Integer) register.get("code");
        if (code != 0) {
            HashMap<String, String> map = new HashMap<>();
            map.put("msg", (String) register.get("msg"));
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/register.html";
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }

    @PostMapping("/userLogin")
    public String login(LoginDTO dto, RedirectAttributes redirectAttributes, HttpSession session) {

        R r = loginService.login(dto);
        Integer code = (Integer) r.get("code");
        //登录失败则重定向到登录页面，并返回错误信息
        if (code != 0) {
            HashMap<String, String> map = new HashMap<>();
            map.put("msg", (String) r.get("msg"));
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/login.html";
        }
        //登录成功后重定向到商城首页，并且将信息存入session
        LinkedHashMap data = (LinkedHashMap) r.get("data");
        ObjectMapper objectMapper = new ObjectMapper();
        MemberRespVO memberRespVO = objectMapper.convertValue(data, MemberRespVO.class);
        log.info("登录成功：{}",memberRespVO.toString());
        session.setAttribute("loginUser",memberRespVO);
        return "redirect:http://gulimall.com";
    }

    @RequestMapping("login.html")
    public String loginPage(HttpSession session) {
        if (session.getAttribute("loginUser") == null) {
            return "login";
        }
        return "redirect:http://gulimall.com";
    }
}
